import React from 'react'
import { renderToString } from 'react-dom/server'
import { StaticRouter } from 'react-router-dom'
import { Provider } from 'react-redux'
import { renderRoutes } from 'react-router-config'
import { Helmet } from 'react-helmet'

// 如果我们能在传给 Provider store 之前，把数据获取到存储到 store 中，就能解决服务器端不渲染的问题
// 而 store 中应该存储什么，我们是不知道的，我们需要结合当前用户的请求地址和路由来做判断
// 如果用户访问 / 路径，我们存储 Home 组件的异步数据
// 如果用户访问 /login 路径，我们就存储 Login 组件的异步数据

export const render = (req, store, routes, context) => {
  const reactContent = renderToString(
    <Provider store={store}>
      <StaticRouter location={req.path} context={context}>
        <div>
          {/* {routes.map(route => (
              <Route {...route} />
            ))} */}
          {renderRoutes(routes)}
        </div>
      </StaticRouter>
    </Provider>
  )
  const helmet = Helmet.renderStatic()

  console.log(context.css)

  const cssStr = context.css.length ? context.css.join('') : ''

  return `
    <html>
      <head>
        ${helmet.title.toString()}
        ${helmet.meta.toString()}
        <style>${cssStr}</style>
      </head>
      <body>
        <div id="root">${reactContent}</div>
        <img src="./images/cat.jpg">
        <script>
            window.context = {
             state: ${JSON.stringify(store.getState())}
            }
        </script>
        <script src='http://localhost:3000/index.js'></script>
      </body>
    </html>`
}
